// packageA/pages/userAdd/userAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
//import { AnimatorControllerStateModel } from 'XrFrame/kanata/lib/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: '',
    items: [
      { value: '1', label: '集体任务' },
      { value: '2', label: '巡检任务' }
    ],
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //部门选择框
    showDepart:false,
    //部门选择数据
    departList:[],
    //搜索部门
    valueSearchDepart:'',
    //考勤规则选择框
    showRule:false,
    //考勤规则选择数据
    ruleList:[],
    //围栏选择框
    showFence:false,
    //围栏选择数据
    fenceList:[],
    //上传的图片
    imgUrls:[],
    //消息人员id
    messagesId:[],
    //人员选择框
    showMessages:false,
    //人员列表
    userList:[],
    //全选/反选
    checkedAll: false,
    //选项数量:
    checkLen:0,
    //部门信息
    departInfo: null,
    //显示上传组件
    showUpload: false,
    //部门id（修改时记录这个值，验证排班时用）
    oldDepart: null,
    //是否改了部门（用于保存后回调）
    isEditDepart: false,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
		valueSearch: '',
		//岗位职责是列表
    jobDutyList: [],
    //工作区域
    showWorkAreaSelect:false,
    //工作区域数据
    selectWorkList:[],
    checkDetailArea:[],


    //-------------------------------------------------------
    taskType:"1",
    // 从数据库获取的列表数据
    taskList: [],
    // 当前展开项的ID（初始不展开任何项）   
    activeName: null,  
    //项目是否必填  
    isDepartRequired:true,
    //选择项目
    projectShow:false,
    //已选择项目列表
    listProjectMap:{},
    //项目权限
    checkedProjectAll:false,
    //任务类型
    // taskType:null,
    //添加任务弹框
    addTaskShow:false,
    //任务对象
    initTaskObj:{

    },
    //审批流程
    taskApproval:new Map()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      listProjectMap: new Map(),
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('人员传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true,
          //编辑时显示头像
          showUpload: false
        })

        //查询考勤规则
        //this.getRuleList();

        //查询围栏
        //this.getFenceList();

        //获取修改的数据
        this.getInfo();
      }else{
        //添加时显示上传头像组件
        this.setData({
          showUpload: true
        })
      }
    }
    this.fetchDataFromDatabase();
    //查询审批流程
    this.findTaskApproval();
  },
  handleTap(e) {
    console.log('选中值:', e)
    //this.setData({ current: e.currentTarget.dataset.value })
    this.setData({
      taskType:e.currentTarget.dataset.value,
    });
  },
  handleChange(e) {
    console.log('选中值:', e.detail.value)
  },
  //查询审批流程
    findTaskApproval(){
      console.log("查询审批流程");
      this.setData({
        departList: []
      })
  
      let param = {
        isAuth: false,
        className: 'taskApprovalProcess',
        data: {
          sortFlag:1,
          searchAll: true,
          selectFields: ['id','name','departMap','selectedDepartments','defaultApproval','member','sortFlag']
        }
      }
      CommonService.goFindList(param).then(res=>{
        console.log(res);
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          console.log("查询审批流程结果");
          console.log(result);
          console.log("result");
          this.setData({
            taskApproval:result[0].departMap
          })
          console.log(this.data);
        }
      }).catch((error) => {
      })
    },
   // 模拟从数据库获取数据
   fetchDataFromDatabase() {
    // 实际项目中使用 wx.request 或云函数调用数据库
    const mockData = [
      // { id: 1, index:0, taskName: "巡检记录", taskRange: "任务范围",taskDescribe:"任务描述",taskRequire:"任务要求",taskPrecautions:"注意事项" },
    ];

    this.setData({
      taskList: mockData
    });
  },
   // 折叠项切换事件
   onCollapseChange(event) {
     console.log(event);
    this.setData({
      activeName: event.detail
    });
  },

  // 主动控制展开指定项（例如点击按钮触发）
  expandItem(id) {
    this.setData({
      activeName: id
    });
  },
  //任务编辑按钮
  handleButtonClick(e){
      console.log(e);
     // let taskEdit = e.currentTarget.dataset.taskObj
      const {taskList} = this.data;
      const taskEdit = taskList[e.currentTarget.dataset.index]
      this.setData({
        addTaskShow:true,
        initTaskObj:taskEdit
      })
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
    //获取时间戳
    const timestamp = Date.parse(new Date()) / 1000;
    console.log(timestamp);
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let user = app.globalData.userInfo;
    console.log(obj);
    console.log(td);
        //权限
        let departObj=app.globalData.userInfo.departObj[0];
        let authArr=[departObj.companyId];
        let dataAuthArr = [...authArr, ...editInfo.projectIds]
        let authSet=new Set(dataAuthArr);
        authArr=Array.from(authSet);
        let saveObj = {
          taskType: parseInt(td.taskType),       
          dataAuthority: {
            depart: authArr
          },
          projectArr:editInfo.projectArr,
          taskList:this.data.taskList,
          projectIds:editInfo.projectIds,
        }

          // 循环 taskList 生成新数组
          const newArray = saveObj.taskList.map(taskItem => {
            return {
              taskType: saveObj.taskType, // 外层的 taskType
              projectIds: saveObj.projectIds, // 外层的 projectIds
              projectArr: saveObj.projectArr, // 外层的 projectArr
              dataAuthority: saveObj.dataAuthority, // 外层的 dataAuthority
              taskObj: taskItem, // 当前循环的 taskList 子对象
              timestamp:timestamp, //时间戳，用于回调函数获取集体任务，加入任务清单
              createUser:{id:user.id,name:user.nickName},
              createLevel:user.departObj[0].level
            };
          });
        let param={
          className:'taskReocrd',
          data:{
            batchSaveData: newArray,       
            isBatchSave:true,
          }
        }       
        //避免表单重复提交
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '数据提交中...'
        });  

        console.log(param);

        CommonService.goSave(param).then(res=>{
          this.setData({
            disabled:false
          })
          if (res.statusCode == 200 && res.data.success == true){
            //如果有集体任务，直接保存到任务清单
            this.saveTaskList(timestamp);
            setTimeout(() => {
              //返回列表页并刷新数据
              this.backAndRefresh();
            }, 1000);
          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }else{
            Toast.fail('操作失败');
          }
        }).catch((error) => {
          Toast.fail('操作失败');
        })
  },

  //如果有集体任务，直接保存到任务清单
  saveTaskList(timestamp){
     let data ={
        timestamp:timestamp,
        taskType:1
     }
     CommonService.collectiveTaskToTaskList(data).then(res=>{

    })

  },


  //选择任务类型
  onchangetype(event){
      console.log("event")
      console.log(event)
      this.setData({
        taskType:event.detail,
      });
      console.log(this.data.taskType);
  },

  //添加任务
  onAddTask(){
    console.log(this.data.taskList.length);
    const taskObj = {
      id:null,
      taskName:"",
      taskDescribe:"",
      taskRange:"",
      imgCountRequire:1,
      taskRequire:"",
      taskPrecautions:"",
      index:this.data.taskList.length
    }
    this.setData({
      addTaskShow:true,
      initTaskObj:taskObj
    })
  },

  //关闭任务弹出层
  onCloseTaskPopup(){
    this.setData({
      addTaskShow:false,
    })
  },

  //电子工牌数据同步es
  addElectronCard(id){
    let param={
      id: id
    }
    CommonService.electronCardSave(param).then(res=>{
      if (res.statusCode == 200){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取修改的数据
  getInfo(){
    let param = {
      id:this.data.id
    }

    CommonService.findPersonnel(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result) {
        let result=res.data.data.result;

        console.log('员工信息回显');
        console.log(result);

        //头像放数组中
        if(result.headImg){
          result.self_img=[result.headImg];
        }
        this.setData({
          departInfo: {id:result.depart,name:result.departName},
          editInfo: result,
          oldDepart: result.depart
        })
        console.log("result");
        console.log(result);
        let checkDetailArea=[];
        if (result.workAreaIdArrP){
          result.workAreaIdArrP.forEach(item=>{
            checkDetailArea.push(item+"")
          })
        }

        this.setData({
          checkDetailArea:checkDetailArea
        })

        //查询部门信息
        this.getDepartById(result.depart);
      }
    }).catch((error) => {
    })
  },

  //获取输入的数量
  onChangePartNum(event) {  
    console.log("event");
    console.log(event);
    let names = 'initTaskObj.imgCountRequire'
    this.setData({
      [names]: event.detail
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //验证imei是否重复
  isExistImei(imei){
    let param={
      imei: imei
    }

    return new Promise((resolve, reject) => {
      CommonService.findPersonnel(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.imei) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //添加任务弹框中确定事件
  onConfirmTask(e){
     console.log(e);
     console.log(this.data);
     const {taskList,initTaskObj} = this.data
     taskList[initTaskObj.index] = initTaskObj
     console.log(taskList);
     this.setData({
      taskList:taskList
    })
    this.onCloseTaskPopup();
  },

  //选择完项目确定事件
  onConfirmUser(){
    console.log("jskdjfkdsjf");
    let listMap=this.data.listProjectMap;
    //map转成数组
    let arr=[...listMap.values()];

    //名字
    let names=[];
    let projectIds = [];
    arr.forEach(item => {
      names.push(item.name);
      projectIds.push(item.id);
		});

    let projectArr='editInfo.projectArr';
    let projectName='editInfo.projectName';
    let projectId='editInfo.projectIds';
    this.setData({
      [projectArr]: arr,
      [projectName]: names,
      [projectId]:projectIds
    })

    this.onCloseDepart();
  },

 //选择项目事件
  onChangeProjectCheck({currentTarget}){
    let detail=currentTarget.dataset.detail;
    let list=this.data.departList;
    let listMap=this.data.listProjectMap;
    console.log(detail);
    console.log(list);
    console.log(listMap);
    list.forEach(item => {
		  if(item.id==detail.id){
        //点击复选框时切换选中
        item.checked=!item.checked;
        if(item.checked){
          //选中的放入已选列表，利用map避免重复
          listMap.set(item.id,item);
        }else{
          //未选中的从map中删除
          listMap.delete(item.id);
        }
      }
    });

    //列表是否全被选中了
    let flag=list.every(item=>{
      return item.checked;
    });

    //是否选中全选
    if(flag){
      this.setData({
        checkedAll: true
      })
    }else{
      this.setData({
        checkedAll: false
      })
    }

    console.log(listMap);

    this.setData({
      departList: list,
      listProjectMap: listMap
    })
  },

  //验证手机号是否重复
  isExist(phone){
    let param={
      isAuth:false,
      className:'user',
      data:{
        nbl: Base64.encode(util.timeFormatDay(new Date())),
        complex:[{or:{"userName":phone,"personalPhone":phone}}],
        selectFields:["id"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },
  clearMessage111(e){
    console.log("0900000000000009090");
    console.log(e);
  },
  //用户输入时清除错误提示
  clearMessage(e) {
    console.log("0000000000000099999999999999999999999999");
    console.log(e);
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false; 
    this.setData(obj);
    const value = e.detail;
    let names = 'initTaskObj.'+field
     // 更新 initTaskObj.name
     this.setData({
      [names]: value
    });
  },

  //任务对象赋值
  setValue(e){
    console.log(e);
    const fieldName = e.currentTarget.dataset.message;
    console.log(fieldName);
   
  },



  //扫码
  onScanCode(e) {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        let imei='editInfo.imei';
        let results=res.result;

        //过滤掉'imei'
        if(results.indexOf('IMEI:')!=-1){
          results=results.substring(5);
        }

        _this.setData({
          [imei]: results
        })
      }
    })
  },

  //显示部门
  onShowDepart(){
    this.setData({
			projectShow: true
    })
    this.getDepartList();
  },

  //查询部门
  getDepartList(){
    console.log("111111111111");
    this.setData({
      departList: []
    })

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
				searchAll: true,
				isProject: true,
        selectFields: ['id','name','regionId','region','fid','fDepart','companyId','company','area','type']
      }
    }
    CommonService.goFindList(param).then(res=>{
      console.log(res);
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            name: item.name,
            id: item.id,
            obj: item
          });
        });
        let map=new Map()
        
        this.data.listProjectMap.forEach(item => {
          map.set(item.id,item)
        })
        arr.forEach(item => {
          if(map.get(item.id)){
            console.log(item);
            item.checked=true;
          }
        });
        this.setData({
          listProjectMap: map,
          departList: arr
        })
        console.log(this.data);
      }
    }).catch((error) => {
    })
  },

  //隐藏部门
  onCloseDepart(){
    this.setData({
      projectShow: false,
    })
  },

  //确认部门
  onConfirmDepart(e){
    let oldDepart=this.data.oldDepart;
    if(oldDepart && oldDepart!=e.detail.value.id){
      this.onCloseDepart();
      Dialog.confirm({
        title: '确定修改所属部门吗？',
        message: '修改后当前人员的排班将删除',
        confirmButtonText:'确定',
        cancelButtonText:'不改了'
      }).then(() => {
        this.departValue(e.detail.value);
        this.setData({
          isEditDepart: true
        })  
      }).catch(() => {
        this.setData({
          isEditDepart: false
        })
      });
    }else{
      this.departValue(e.detail.value);
    }  
  },
  
  //确认部门的值
  departValue(val){
    let depart='editInfo.depart';
    let departName='editInfo.departName';
    let regionId='editInfo.regionId';
    let obj=val.obj;

    this.setData({
      [depart]: val.id,
      [departName]: val.text,
      //项目的大区(无大区取上级)存入工牌的数据权限
      [regionId]: obj.regionId ? obj.regionId : obj.fid,
      //选择的部门信息，用于匹配考勤规则和围栏
      departInfo: obj,
      disabled: false
    })

    this.onCloseDepart();
  },

  //搜索部门
  onChangeDepartVal(e){
    this.setData({
      valueSearchDepart: e.detail
    })
    this.getDepartList();
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;

    if(imgUrls.length){
      this.setData({
        imgUrls: imgUrls
      })
    }
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示考勤规则
  onShowRule(){
    if(this.data.editInfo.depart){
      this.setData({
        showRule: true
      })
      this.getRuleList();
    }else{
      Toast.fail('请先选择部门');
    }
  },

  //查询考勤规则
  getRuleList(){
    let param = {
      isAuth: false,
      className: 'clockRule',
      data: {
        searchAll: true,
        selectFields: ['id','ruleName']
      }
    }

    //查询选择的部门、上级部门、大区、顶级部门的考勤规则
    try {
      let info=this.data.departInfo;
      let arr=[info.id];
      if(info.companyId){
        arr.push(info.companyId);
      }
      if(info.fid){
        arr.push(info.fid);
      }
      if(info.regionId){
        arr.push(info.regionId);
      }
      param.data.departId = arr;
    } catch (e) {}

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.ruleName,
            id:item.id
          });
        });
        this.setData({
          ruleList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏考勤规则
  onCloseRule(){
    this.setData({
      showRule: false
    })
  },

  //确认考勤规则
  onConfirmRule(e){
    let clockRuleId='editInfo.clockRuleId';
    let clockRuleName='editInfo.clockRuleName';
    this.setData({
      [clockRuleId]: e.detail.value.id,
      [clockRuleName]: e.detail.value.text,
      disabled: false
    })
    this.onCloseRule();
  },

  //显示围栏
  onShowFence(){
    if(this.data.editInfo.depart){
      this.setData({
        showFence: true
      })
      this.getFenceList();
    }else{
      Toast.fail('请先选择部门');
    }
  },

  //查询围栏
  getFenceList(){
    let param = {
      isAuth: false,
      className: 'personnelFence',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //查询选择的部门、上级部门、大区、顶级部门的围栏
    try {
      let info=this.data.departInfo;
      let arr=[info.id];
      if(info.companyId){
        arr.push(info.companyId);
      }
      if(info.fid){
        arr.push(info.fid);
      }
      if(info.regionId){
        arr.push(info.regionId);
      }
      param.data.departId = arr;
    } catch (e) {}

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          fenceList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏围栏
  onCloseFence(){
    this.setData({
      showFence: false
    })
  },

  //确认围栏
  onConfirmFence(e){
    let fenceId='editInfo.fenceId';
    let fenceName='editInfo.fenceName';
    this.setData({
      [fenceId]: e.detail.value.id,
      [fenceName]: e.detail.value.text,
      disabled: false
    })
    this.onCloseFence();
  },

  //显示人员选择框
  onShowMessages(){
    this.setData({
			showMessages: true
    })
    //查询人员
    this.getUserList();
  },

  //查询人员
  getUserList(){
    let param = {
      depart: [this.data.editInfo.depart]
    }

    CommonService.findPersonnelAll(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            name:item.nickName
          });
        });

        this.setData({
          userList: arr,
          checkLen:arr.length
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏项目选择框
  onCloseMessages(){
    this.setData({
			showMessages: false
    })
  },

  //勾选人员
  onChangeUser(event) {
    this.setData({
      messagesId: event.detail
    })

    if(event.detail.length==this.data.checkLen){
      this.setData({
        checkedAll: true,
      })
    }else{
      this.setData({
        checkedAll: false,
      })
    }
  },

  //点击全选
  onChangeAll(event) {
    this.setData({
      checkedAll: event.detail,
    })

    if(event.detail){
      let list=this.data.userList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+"");
      })
      this.setData({
        messagesId: arr,
      })
    }else{
      this.setData({
        messagesId: [],
      })
    }
  },

  //确认人员
  onConfirmMessages(){
    let list=this.data.userList;
    let idArr=this.data.messagesId;

    let names=[];
    let arr=[];
    for(let i=0;i<list.length;i++){
      idArr.forEach(item => {
        if (item==list[i].id){
          names.push(list[i].name);
          arr.push(list[i]);
        }
      });
    }

    let messagesName='editInfo.messagesName';
    let messagesReceivingUser='editInfo.messagesReceivingUser';
    this.setData({
      [messagesName]: names,
      [messagesReceivingUser]: arr
    })

    this.onCloseMessages();
  },

  //查询部门信息
  getDepartById(departId){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id: departId,
        selectFields: ['id','name','regionId','region','fid','fDepart','companyId','company','area','type']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        this.setData({
          departInfo: result[0]
        })
      }
    }).catch((error) => {
    })
  },

  //显示上传图片组件
  onShowUpload(){
    this.setData({
			showUpload: true
		})
  },

  //删除今天之后的排班
  deleteShift(){
    let param={
      imei: this.data.editInfo.imei
    }
    CommonService.deleteShift(param).then(res=>{
    }).catch((error) => {
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;  

    //岗位
    if(field=='jobPost'){
      //是否已选部门
      if(this.data.editInfo.departName){
        this.setData({
          showSelect: true,
          selectField: field,
          selectTitle: '岗位',
          showSelectSearch: true
        })
        this.getStationStep();
      }else{
        Toast.fail('请选择部门');
        return;
      }
      
    }else{
			if(field=='workArea'){
				this.setData({         
          selectTitle: '清洁区域',
          showSelectSearch: true
        })
        this.getWorkAreaList();
			}

			if(field=='jobDuty'){
				this.setData({        
          selectTitle: '岗位职责',
					showSelectSearch: false,
					selectList: this.data.jobDutyList
        })
			}

      this.setData({
        showSelect: true,
        selectField: field
      })
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //岗位
    if(selectField=='jobPost'){
      console.log(e.detail.value.obj);
  
      //岗位id（表s_station_step中id）
      let stationStepId='editInfo.stationStepId';
      //岗位名称
      let jobPost='editInfo.jobPost';
      //岗位步数
      let fullStep='editInfo.fullStep';
      //工作时间
      let workTime = 'editInfo.workTime';

			let oo = e.detail.value.obj;
			
			//岗位职责选项
			let jobDutyList = [];
			if(oo.jobDuty && oo.jobDuty.length){
				oo.jobDuty.forEach(item=>{
					jobDutyList.push({
						id: item.id,
						text: item.name
					});
				});
			}

      this.setData({
        [stationStepId]: oo.stationStepId,
				[jobPost]: oo.jobPost,
				jobDutyList: jobDutyList,
        [fullStep]: oo.fullStep,
        [workTime]: oo.workTime,
      })
		}
		
		//清洁区域
    if(selectField=='workArea'){
			id = 'editInfo.workAreaId';
		 	name = 'editInfo.workAreaName';
		}
		
		//岗位职责
    if(selectField=='jobDuty'){      
		 id = 'editInfo.jobDutyId';
		 name = 'editInfo.jobDutyName';
		}

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //岗位
    if(selectField=='jobPost'){
			this.getStationStep();			
    }
	},
	
	//改变选择框
	onChangeSelect(){
		let selectField = this.data.selectField;

		//改变岗位时清空职责
    if(selectField=='jobPost'){
			console.log('11111111111');
			let jobDutyId = 'editInfo.jobDutyId';
			let jobDutyName = 'editInfo.jobDutyName';
			 
			this.setData({
				[jobDutyId]: null,
				[jobDutyName]: null
			})
    }
	},

  //隐藏区域
  onCloseArea(){
    this.setData({
      showWorkAreaSelect: false
    })
  },

  //查询岗位
  getStationStep(){
    let departInfo = this.data.departInfo;

    let param = {
      isAuth: true,
      className: 'stationStep',
      data: {
        searchAll: true,
        //选择部门的顶级部门，这样任何用户登录都可以查到
        'member.id': departInfo.companyId,
        selectFields: ['id','name','step','jobDuty','workTime'],
        nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    if(this.data.valueSearch){
      param.data.name = '%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
				let result=res.data.data.result;
				console.log('岗位');
				console.log(result);

        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj:{
              stationStepId: item.id,
              jobPost: item.name,
							fullStep: item.step,
              jobDuty: item.jobDuty,
              workTime:item.workTime
            }          
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //改变部门
  onChangeDepart(){
    //清空岗位
    let stationStepId = 'editInfo.stationStepId';
    let jobPost = 'editInfo.jobPost';
		let fullStep = 'editInfo.fullStep';
		let jobDuty = 'editInfo.jobDuty';

    this.setData({
      [stationStepId]: null,
      [jobPost]: null,
			[fullStep]: null,
			[jobDuty]: null
    })
	},
	
	//查询清洁区域
	getWorkAreaList(){
		let param = {
      isAuth: true,
      className: 'workArea',
      data: {
        searchAll: true,
        selectFields: ['id','name','project']
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },
  
//-------------------------------------------工作区域---------------------------------------------------------------------------
  //显示工作区域选择框
  onShowWorkAreaPersonnel(e){
    this.setData({
      selectWorkList:[],
    })
    if(this.data.editInfo.departName){
      let dataset=e.currentTarget.dataset;
      let field=dataset.field;
      console.log(field);
  
      this.setData({
        selectTitle:"工作区域",
        showWorkAreaSelect: true,
        selectField: field
      })
  
      this.getWorkAreaPList();
    }else{
      Toast.fail('请选择项目');
      return;
    }
},

  //查询工作区域
  getWorkAreaPList(){
    let departInfo = this.data.departInfo;
    console.log(this.data);
    let param = {
      isAuth: true,
      className: 'workAreaP',
      data: {
        searchAll: true,
        projectId:departInfo.id,
        selectFields: ['id','name','workAreaTypeName','attribute'],
        sort:{workAreaTypeId:1,attribute:1,name:1}
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }
    console.log(param);
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log("result");
        console.log(result);
        let arr=[];
        result.forEach(item => {
          arr.push({
            id:item.id,
            name:item.attribute+"-"+item.name,
          });
        });

        this.setData({
          selectWorkList: arr
        })
      }
    }).catch((error) => {
    })
  },


  //点击区域明细选项
 onChangeDetailArea(event) {
  console.log(event);
 this.setData({
   checkDetailArea: event.detail
 })

 if(event.detail.length==this.data.checkLenArea){
   this.setData({
     checkedAllArea: true
   })
 }else{
   this.setData({
     checkedAllArea: false
   })
 }
},


//确定清洁区域按钮
onConfirmArea(){
  console.log(this.data.checkDetailArea);
  let checkDetail=this.data.checkDetailArea;
  //所有工作区域
  if(checkDetail.length){
    let list=this.data.selectWorkList;
    let arr=[];
    let names=[];
    let idarr=[];
    list.forEach(item => {
      for(let i=0;i<checkDetail.length;i++){
        if(checkDetail[i]==item.id){
          console.log("相等");
          arr.push(item);
          names.push(item.name);
          idarr.push(item.id);
        }
      }
    });
     //显示名称
     let self_name='editInfo.workAreaNameP';
     //接口保存数据
     let items='editInfo.workAreaP';
     let self_ids = 'editInfo.workAreaIdArrP'
     this.setData({
      [self_name]: names,
      [items]: arr,
      [self_ids]:idarr,
      showWorkAreaSelect: false,
      disabled: false
    })
  }else{
    Toast.fail('请选择清洁区域');
  }
},


//-------------------------------------------工作区域---------------------------------------------------------------------------


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
